import { createApp } from "vue";
import { createPinia } from "pinia";
import { useVariableStore } from "./stores/variable.ts";
import "@/lib/style.css";
import App from "./App.vue";
import umrp from "@/lib/index.ts";
import router from "./router/index.ts";
import "./style.scss";
import * as _ from "@usemathx/utils";

function addTapListener(element: any, callback: any) {
  let startX: number, startY: number, startTime: number;
  const maxMove = 10; // 最大允许移动距离(px)
  const maxDuration = 300; // 最长允许持续时间(ms)

  element.addEventListener(
    "touchstart",
    function (e: any) {
      startX = e.touches[0].clientX;
      startY = e.touches[0].clientY;
      startTime = Date.now();
    },
    { passive: true }
  );

  element.addEventListener(
    "touchend",
    function (e: any) {
      if (!startTime) return;

      const endX = e.changedTouches[0].clientX;
      const endY = e.changedTouches[0].clientY;
      const duration = Date.now() - startTime;

      // 判断是否满足tap条件
      if (Math.abs(endX - startX) < maxMove && Math.abs(endY - startY) < maxMove && duration < maxDuration) {
        callback(e);
      }

      startTime = 0; // 重置状态
    },
    { passive: true }
  );
}

function isMobile() {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

declare module "vue" {
  interface ComponentCustomProperties {
    $state: (key: string, value: any) => void;
  }
}

router.beforeEach((to) => {
  const titleElement = document.querySelector("title");
  if (titleElement && to.meta.title) {
    titleElement.innerText = to.meta.title.toString();
  }
});

const app = createApp(App);
app.use(createPinia());
app.use(router);
app.directive("state", {
  mounted: (el, binding) => {
    const variableStore = useVariableStore();
    el.addEventListener(binding.arg, () => {
      let key = Object.keys(binding.value)[0];
      variableStore.variable[key] = binding.value[key];
    });
  },
});
app.directive("visible", {
  mounted: (el, binding) => {
    const variableStore = useVariableStore();
    const key = Object.keys(binding.value)[0];

    el.style.display = variableStore.variable[key] === binding.value[key] ? "" : "none";

    variableStore.$subscribe((_: any, state: any) => {
      el.style.display = state.variable[key] === binding.value[key] ? "" : "none";
    });
  },
});
app.directive("route", {
  mounted: (el, binding) => {
    el.style.cursor = "pointer";
    if (isMobile()) {
      addTapListener(el, () => {
        router.push({ name: binding.value });
      });
    } else {
      el.addEventListener("click", () => {
        router.push({ name: binding.value });
      });
    }
  },
});

umrp.install(app);
app.mount("#app");
